package com.mcxx.modules.temporary.controller;

import com.alibaba.fastjson.JSON;
import com.mcxx.modules.temporary.service.TempFundPayService;
import com.mcxx.modules.miniSalvation.fundpay.param.FundPayParam;
import com.mcxx.modules.temporary.fundpay.dto.TmpFundPayDTO;
import com.mcxx.modules.temporary.fundpay.param.TmpFundPayParam;
import com.mcxx.modules.temporary.fundpay.service.read.TmpFundPayFamilyReadService;
import com.mcxx.modules.temporary.fundpay.service.read.TmpFundPayReadService;
import com.mcxx.service.DefaultRestService;
import com.mcxx.util.Constant;
import com.mcxx.util.FileExportUtil;
import com.mcxx.util.ZipInfoUtil;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.restservice.annotation.RestService;
import com.yinhai.ta404.core.restservice.requestbean.PageParam;
import com.yinhai.ta404.core.restservice.resultbean.Page;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.validate.annotation.V;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Validated
@Api("名册管理")
@RestService({"temporary/fundpay/v2"})
public class TempFundPayController extends DefaultRestService {


    private static final Logger logger = LoggerFactory.getLogger(TempFundPayController.class);

    @Autowired
    private TempFundPayService tempFundPayService;
    @Autowired
    private TmpFundPayReadService tmpFundPayReadService;
    @Autowired
    private TmpFundPayFamilyReadService tmpFundPayFamilyReadService;


    @PostMapping("getFundPayList")
    @ApiOperation("获取资金发放名册")
    public  void getFundPayList(TmpFundPayParam param, PageParam pageParam){
        log.info("查询资金发放列表, 参数：{}，分页参数：{}", JSON.toJSONString(param), JSON.toJSONString(pageParam));
        Page page = tmpFundPayReadService.getFundPayList(param, pageParam, getCurUserAccount());
        setPageBean(page);
        log.info("查询资金发放列表,结果：{}", JSON.toJSONString(page));
    }


    @PostMapping("getFundPayName")
    @ApiOperation("得到资金发放名册名字")
    public void getFundPayName(@V({"notnull"}) String payWay){
        log.info("得到资金发放名册名字, 发放类型：{}", payWay);
        String fundName = tmpFundPayReadService.getFundName(payWay, getCurUserAccount().getAreaCode());
        setData(fundName);
        log.info("得到资金发放名册名字, 结果：{}", fundName);
    }


    @PostMapping("addFundPay")
    @ApiOperation("创建资金发放名册")
    public void addFundPay(TmpFundPayDTO tmpFundPayDTO){
        log.info("创建资金发放名册,参数：{}", tmpFundPayDTO);
        UserAccountVo userAccountVo = this.getCurUserAccount();
        tmpFundPayDTO.setAreaCode(userAccountVo.getAreaCode());
        tmpFundPayDTO.setOrgId(userAccountVo.getOrgId());
        tempFundPayService.addFundPay(tmpFundPayDTO, userAccountVo);
        setData(true);
        log.info("创建资金发放名册,结果：{}", true);
    }


    @PostMapping("verifyOrderNoticeState")
    @ApiOperation("验证保障金发放名册中是否存在未结束公示的")
    public void verifyOrderNoticeState(@V("notnull")String fundPayId){
        logger.info("验证保障金发放名册中是否存在未结束公示的,id：{}", fundPayId);
        int rst = tmpFundPayFamilyReadService.verifyNoCompleteNotice(fundPayId);
        setData(rst);
        logger.info("验证保障金发放名册中是否存在未结束公示的,业务条数：{}", rst);
    }


    @PostMapping("confirmFundPay")
    @ApiOperation("将名册状态修改为已确认")
        public void confirmFundPay(@V({"notnull"}) String fundPayId){
        log.info("将名册状态修改为已确认,参数：{}", fundPayId);
        tempFundPayService.confirmFundPay(fundPayId, getCurUserAccount());
        setData("名册确认成功");
        log.info("将名册状态修改为已确认结束");
    }


    @PostMapping("verifySyncFundpay")
    @ApiOperation("检查发放名册是否可以同步数据")
    public void verifySyncFundpay(@V("notnull") String fundPayId){
        logger.info("同步发放名册至财政发放系统前，检查发放名册是否可以同步数据到发放系统,id：{}", fundPayId);
        String msg = tempFundPayService.checkCanSyncFundpayData(fundPayId);
        logger.info("结果：" + msg);
        setData(msg);
    }


    @PostMapping("syncFundpayData")
    @ApiOperation("同步发放名册至财政发放系统")
    public void syncFundpayData(@V("notnull") String fundPayId){
        logger.info("同步发放名册至财政发放系统,id：{}", fundPayId);
        String msg = tempFundPayService.syncFundpayData(fundPayId);
        logger.info("结果：" + msg);
        setData(msg);
    }


    @PostMapping({"downloadExceptionList"})
    public void downLoadRescueList(HttpServletResponse response,@RequestBody FundPayParam param) throws IOException {
        ExcelInfo excelInfo = tempFundPayService.exportExcel(param.getFundPayId());
        if(null != excelInfo){
            ZipInfoUtil.exportZipResponse(response, excelInfo, this.getCurUserId());
        }
    }


    @PostMapping("delFundPay")
    @ApiOperation("删除名册")
    public void delFundPay(@RequestPart List<String> fundPayIdList){
        log.info("删除名册,参数：{}", fundPayIdList);

       String retMsg = tempFundPayService.delFundPay(fundPayIdList);

        setData(retMsg);

        log.info("删除名册结束，结果是{}",true);
    }


    @PostMapping("delCapitalFundPayObjectList")
    @ApiOperation("删除已选资金发放对象")
    public void delCapitalFundPayObjectList(@V("notnull") String fundPayId, @V("notnull") @RequestPart List<String> familyIdList){
        log.info("删除已选资金发放对象,参数：{}", fundPayId);
        tempFundPayService.delFundPayObjectList(fundPayId, familyIdList);
        setSuccess();
        log.info("删除已选资金发放对象，结果是:{}", true);
    }


    @PostMapping("getNoSaveCapitalObjectList")
    @ApiOperation("获取未绑定名册的对象")
    public void getNoSaveCapitalObjectList(TmpFundPayParam tmpFundPayParam, PageParam pageParam){
        log.info("获取未绑定名册的对象,参数：{}", tmpFundPayParam);
        Page page = tempFundPayService.getNoSaveCapitalObjectList(tmpFundPayParam, pageParam, getCurUserAccount());
        this.setPageBean(page);
        log.info("获取未绑定名册的对象,结果：{}", page);
    }


    @PostMapping("getCapitalObjectList")
    @ApiOperation("查询资金发放列表明细")
    public void getCapitalObjectList(@V("notnull") TmpFundPayParam fundPayFamilyParam, @V("notnull") PageParam pageParam){
        logger.info("查询资金发放列表明细,参数：{}", fundPayFamilyParam);
        Page page = tmpFundPayFamilyReadService.getCapitalFamilyList(fundPayFamilyParam, pageParam, getCurUserAccount());
        this.setPageBean(page);
        logger.info("查询资金发放列表明细,结果：{}", page);
    }


    @PostMapping("saveCapitalFundPayObject")
    @ApiOperation("添加已选资金发放对象")
    public void saveCapitalFundPayObject(@V("notnull") String fundPayId, @V("notnull") Date payDate, @V("notnull") @RequestPart List<String> orderIdList){
        log.info("保存已选资金发放对象,参数：{}", fundPayId);

        TmpFundPayDTO tmpFundPayDTO = new TmpFundPayDTO();
        tmpFundPayDTO.setId(fundPayId);
        tmpFundPayDTO.setPayDate(payDate);
        tempFundPayService.addCapitalFundPayObject(tmpFundPayDTO, orderIdList);
        setSuccess();
        log.info("保存已选资金发放对象,结果是：{}", true);
    }


    @PostMapping("getTmpFundPayCount")
    @ApiOperation("资金发放名册明细统计")
    public void getTmpFundPayCount(TmpFundPayParam param){
        log.info("资金发放名册明细统计,参数：{}", param);
        Map<String, String> rstMap = tmpFundPayReadService.getTmpFundPayCount(param, getCurUserAccount());
        this.setData(rstMap);
        log.info("资金发放名册明细统计,结果：{}");
    }


    @PostMapping("getTmpFundPayDetail")
    @ApiOperation("资金发放名册明细")
    public void getTmpFundPayDetail(TmpFundPayParam param, PageParam pageParam){
        log.info("资金发放名册明细,参数：{}", param);
        Page page = tmpFundPayReadService.getTmpFundPayDetail(param, pageParam, getCurUserAccount());
        setPageBean(page);
        log.info("资金发放名册明细,结果：{}");
    }


    @PostMapping({"downLoadFundPayList"})
    public void downLoadFundPayList(HttpServletResponse response, @RequestBody TmpFundPayParam param) throws IOException {
        log.info("正在导出临时救助资金发放名册，请求参数：{}", JSON.toJSONString(param));
        ExcelInfo excelInfo = tempFundPayService.exportFundPayList(param, getCurUserAccount());
        if(null != excelInfo){
            ZipInfoUtil.exportZipResponse(response, excelInfo, this.getCurUserId());
        }
    }


    @PostMapping({"downLoadCapitalList"})
    public void downLoadCapitalList(HttpServletResponse response, @RequestBody TmpFundPayParam param) throws IOException {
        log.info("正在导出临时救助资金发放明细，请求参数：{}", JSON.toJSONString(param));
        ExcelInfo excelInfo = tempFundPayService.exportFundPayList(param, getCurUserAccount());
        if(null != excelInfo){
            FileExportUtil.exportFileResponse(response, excelInfo, getCurUserAccount().getAreaName());
//            ZipInfoUtil.exportZipResponse(response, excelInfo, this.getCurUserId());
        }
    }


    @PostMapping({"downLoadTempFundPayList"})
    public void downLoadTempFundPayList(HttpServletResponse response, @RequestBody FundPayParam param) {
        log.info("正在导出临时救助资金发放名册，请求参数：{}", JSON.toJSONString(param));
        ExcelInfo excelInfo = tempFundPayService.exportExcelTempFundPay(param.getExportType(),param.getIdsList(),param,getCurUserAccount());
        if(null != excelInfo){
            try {
                FileExportUtil.exportFileResponse(response, excelInfo, getCurUserAccount().getAreaName());
//                ZipInfoUtil.exportZipResponse(response, excelInfo, this.getCurUserId());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @PostMapping("cancelFundPay")
    @ApiOperation("将名册状态修改为撤销")
    public void cancelFundPay(@RequestPart List<String> fundPayIdList){
        log.info("将名册状态修改为撤销,参数：{}", fundPayIdList);
        String retMsg = tempFundPayService.cancelFundPay(fundPayIdList);
        setData(retMsg);

        log.info("将名册状态修改为撤销结束");
    }


    private String packageRstMsg(Map<String, List<String>> rstMap){
        StringBuffer rstMsg = new StringBuffer();
        if(rstMap.containsKey("success")){
            rstMsg.append("成功【").append(rstMap.get("success").size()).append("】条\n");
        }
        if(rstMap.containsKey("fail")){
            rstMsg.append("失败【").append(rstMap.get("fail").size()).append("】条");
        }
        return rstMsg.toString();
    }


    @PostMapping("getFundpayExceptionList")
    @ApiOperation("查看该名册异常数据")
    public void getFundpayExceptionList(@V("notnull") String fundPayId, PageParam pageParam){
        logger.info("根据名册查看该名册生成过程中是否存在异常情况,id：{}", fundPayId);
        Page page = tempFundPayService.getPageFundpayException(fundPayId, pageParam);
        logger.info("结果：" + page.getPageSize());
        setPageBean(page);
    }


    @PostMapping({"downCapitalObjectList"})
    public void downCapitalObjectList(HttpServletResponse response,@RequestBody TmpFundPayParam param) throws IOException {
        param.setBusinessType(Constant.BusinessCode.LINSHI);
        ExcelInfo excelInfo = tempFundPayService.exportCapitalObjectList(param,getCurUserAccount());
        if(null != excelInfo){
            FileExportUtil.exportFileResponse(response, excelInfo, getCurUserAccount().getAreaName());
//            ZipInfoUtil.exportZipResponse(response, excelInfo, this.getCurUserId());
        }
    }
}
